import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import DashboardView from '../views/DashboardView.vue'
import QuitProfileView from '../views/QuitProfileView.vue'
import DailyRecordView from '../views/DailyRecordView.vue'
import MilestoneView from '../views/MilestoneView.vue'
import HealthTipsView from '../views/HealthTipsView.vue'
import CravingLogView from '../views/CravingLogView.vue'
import UserMilestoneView from '../views/UserMilestoneView.vue'
import AIAssistantView from '../views/AIAssistantView.vue'

const routes = [
  {
    path: '/',
    name: 'Login',
    component: LoginView,
    meta: {
      title: '登录 - HMM健康戒烟助手',
      requiresAuth: false
    }
  },
  {
    path: '/login',
    name: 'LoginPage',
    component: LoginView,
    meta: {
      title: '登录 - HMM健康戒烟助手',
      requiresAuth: false
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: DashboardView,
    meta: {
      title: '仪表板 - HMM健康戒烟助手',
      requiresAuth: true
    }
  },
  {
    path: '/quit-profile',
    name: 'QuitProfile',
    component: QuitProfileView,
    meta: {
      title: '戒烟档案 - HMM健康戒烟助手',
      requiresAuth: true
    }
  },
  {
    path: '/daily-record',
    name: 'DailyRecord',
    component: DailyRecordView,
    meta: {
      title: '每日记录 - HMM健康戒烟助手',
      requiresAuth: true
    }
  },
  {
    path: '/milestones',
    name: 'Milestones',
    component: MilestoneView,
    meta: {
      title: '戒烟里程碑 - HMM健康戒烟助手',
      requiresAuth: true
    }
  },
  {
    path: '/health-tips',
    name: 'HealthTips',
    component: HealthTipsView,
    meta: {
      title: '健康建议 - HMM健康戒烟助手',
      requiresAuth: true
    }
  },
  {
    path: '/craving-log',
    name: 'CravingLog',
    component: CravingLogView,
    meta: {
      title: '烟瘾记录 - HMM健康戒烟助手',
      requiresAuth: true
    }
  },
  {
    path: '/achievements',
    name: 'UserMilestone',
    component: UserMilestoneView,
    meta: {
      title: '我的成就 - HMM健康戒烟助手',
      requiresAuth: true
    }
  },
  {
    path: '/ai-assistant',
    name: 'AIAssistant',
    component: AIAssistantView,
    meta: {
      title: 'AI助手 - HMM健康戒烟助手',
      requiresAuth: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }

  // 检查认证状态
  const token = localStorage.getItem('token')
  const requiresAuth = to.meta.requiresAuth

  if (requiresAuth && !token) {
    // 需要认证但没有token，跳转到登录页
    next('/login')
  } else if (!requiresAuth && token && (to.path === '/' || to.path === '/login')) {
    // 已登录用户访问登录页，跳转到仪表板
    next('/dashboard')
  } else {
    next()
  }
})

export default router